package com.gin.kotlin.no_gay_alliance.fragment.pm

import com.gin.kotlin.no_gay_alliance.adapter.pm.PrivateMessageAdapter
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.base.RecyclerViewScrollListener
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.FragmentPrivateMessageListBinding
import com.gin.kotlin.no_gay_alliance.model.PrivateMessageListModel
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.PrivateMessageListProvider

class PrivateMessageListFragment : AbstractBindingFragment<FragmentPrivateMessageListBinding>(), RCallback<PrivateMessageListModel, Int> {
    private var hasNext: Boolean = true
    private lateinit var adapter: PrivateMessageAdapter
    private var page = 1

    override fun onCreateView() {
        val b = this.b ?: return
        this.adapter = PrivateMessageAdapter(requireContext(), handler!!)
        b.recyclerView.adapter = this.adapter
        b.swipeRefreshLayout.setOnRefreshListener {
            page = 1
            adapter.clear()
            request(true)
        }
        b.recyclerView.addOnScrollListener(RecyclerViewScrollListener(scrollToBottomListener = object : RecyclerViewScrollListener.ScrollToBottomListener {
            override fun onScrollToBottom() {
                if (hasNext){
                    toast("正在加载...")
                    request(true)
                }
            }
        }))

        request()
    }


    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = true
        PrivateMessageListProvider.getInstance().enqueue(page, ignoreCache = ignoreCache, callback = this)
    }

    override fun onSuccess(data: PrivateMessageListModel, ignoreCache: Boolean) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = false
        this.adapter.pushData(data.data)
        this.hasNext = data.hasNext
        page++
    }

    override fun onError(errorMessage: String) {
        toastLong(errorMessage)
    }
}